#include <vector>
#include <set>
#include<algorithm>
using namespace std;

// 给定一个无重复元素的数组 candidates 和一个目标数 target 
// ，找出 candidates 中所有可以使数字和为 target 的组合。

// candidates 中的数字可以无限制重复被选取。

// 1.回溯+剪枝算法
class Solution
{
public:
    vector<vector<int>> result;
    void subSum(vector<int> &cadidates, vector<int> tmp_res, int target, int sub)
    {
        if (target - sub == 0)
        {
            tmp_res.push_back(sub);
            result.push_back(tmp_res);
            return;
        }
        if (target - sub > 0)
        {
            tmp_res.push_back(sub);
            target = target - sub;
            for (int i = 0; i < cadidates.size(); i++)
            {
                subSum(cadidates, tmp_res, target, cadidates.at(i));
            }
        }
        if (target - sub < 0)
        {
            return;
        }
    }
    vector<vector<int>> combinationSum(vector<int> &candidates, int target)
    {
        vector<int> tmp_res;
        for (int i = 0; i < candidates.size(); i++)
        {
            subSum(candidates, tmp_res, target, candidates.at(i));
        }
        //result去重
        for (int j = 0; j < result.size(); j++)
        {
            //先把每个数组排序
            sort(result[j].begin(),result[j].end());
        }
        set<vector<int>> set_tmp (result.begin(),result.end());
        result.assign(set_tmp.begin(),set_tmp.end());

        return result;
    }
};